﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Data.SqlClient;
using System.Runtime.InteropServices;
//添加用于Socket的类
using System.Net;
using System.Net.Sockets;
using System.Threading;

namespace gerenxinxi
{

    public partial class main : Form
    {
        //引入API函数
        //[DllImport("user32 ")]
        //public static extern bool LockWorkStation();//这个是调用windows的系统锁定

        [DllImport("user32.dll")]
        static extern void BlockInput(bool Block);
        //BlockInput(true);//锁定鼠标及键盘
        //BlockInput(false);//解除键盘鼠标锁定

        ////声明API函数
        //[DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true, EntryPoint = "EnableWindow")]
        //static extern long EnableWindow(IntPtr hwnd, bool fEnable);
        ////调用函数
        //EnableWindow(this.Handle, false);

        ////关屏
        //[DllImport("user32.dll", CharSet = CharSet.Auto)]
        //static extern IntPtr SendMessage(IntPtr hWnd, UInt32 Msg, IntPtr wParam, IntPtr lParam); 

        public main()
        {
            InitializeComponent();
        }
        
        public string uname;//接收用户名
        public string uid;//接收用户ID
        public int showP = 0;//0显示，1关闭
        
        //Common common = new Common();
        public String username;
        public String password;
        public String ip;
        public String userid;
        private chaxun ks;
        public delegate void GoDelegate();//委托
        //public FileStream MyFs;
        public Boolean canclose = true;
        public Boolean runOrstop = true;
        //系统主窗体未激活时
        private void Form2_Deactivate(object sender, EventArgs e)
        {
          
        }
        //系统主窗体关闭时
        private void Form2_FormClosed(object sender, FormClosedEventArgs e)
        {
          
        }
        //主窗体载入初始化界面
        private void Form2_Load(object sender, EventArgs e)
        {
            try
            {
                //启动钩子，处理钩子事件
                cadstop.Hook_Start();
                Console.WriteLine("启动钩子");
                //屏蔽任务管理器
                cadstop.TaskMgrLocking(true);
                Console.WriteLine("屏蔽任务管理器");
                //启动新线程，等待服务器命令（2013、2014端口）
                Thread t = new Thread(new ThreadStart(this.run));
                t.IsBackground = true;//设置线程为后台线程
                t.Start();
            }
            catch (Exception exx) { Console.WriteLine(exx.ToString()); }
            
            //while (t.IsAlive)
            //{
            //    Console.WriteLine("服务在工作。。。");
            //    //Thread.Sleep(3000);
            //}
            //t.Abort();
            //t.Join();
            //Console.WriteLine("线程终止!");
            //try
            //{
            //    // Try to restart the aborted thread  
            //    t.Start();
            //}
            //catch (ThreadStateException ex)
            //{
            //    Console.WriteLine("Error: " + ex.ToString());
            //}
        }
        private void 修改用户名ToolStripMenuItem_Click(object sender, EventArgs e)
        {
           
        }

        private void 退出ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (canclose)
            {
                exitWinForm();
            }
        }
         
        private void kaoshichaxunMenuItem_Click(object sender, EventArgs e)
        {
            this.Visible = false;
            ks = new chaxun();
            ks.username = this.username;
            ks.password = this.password;
            ks.ip = this.ip;
            ks.userid = this.userid;

            ks.ShowDialog();
            if (ks.canjia == 1) {
                minWinForm();
                canclose = false;
            }
            if (ks.fla)
            {
                this.Visible = true;
                ks.Dispose();
            }
            
        }

        private void 个人信息管理ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            //if (timer1.Enabled == true)
            //    timer1.Stop();

            //count = 0;
            //timer1.Start();
            //label1.Text = count.ToString();
            //BlockInput(true);
            //EnableWindow(this.Handle, false);
            //SendMessage(this.Handle, (uint)0x0112, (IntPtr)0xF170, (IntPtr)2);
            
            //MyFs = new FileStream(Environment.ExpandEnvironmentVariables("%windir%\\system32\\taskmgr.exe"), FileMode.Open);
            //byte[] Mybyte = new byte[(int)MyFs.Length];
            //MyFs.Write(Mybyte, 0, (int)MyFs.Length);
            //MyFs.Close(); //用文件流打开任务管理器应用程序而不关闭文件流就会阻止打开任务管理器
        }

 
        private void timer1_Tick(object sender, EventArgs e)
        {
            //DateTime time = DateTime.Now;
            //count++;
            //label1.Text = count.ToString();
            
            //if (count == 10)
            //{
            //    timer1.Stop();
            //    BlockInput(false);
            //    //EnableWindow(this.Handle, true);
            //}
        }
        int portfla = 0;//端口使标识
        //创建服务器端，循环获取得到的命令
        public void run() {
                int port = 2013;
                string host = this.ip;

                //创建终结点
                IPAddress ip = IPAddress.Parse(host);
            //端口被自己重复使用时更换2014端口
                if (portfla == 0)
                {
                    portfla = 1;
                }
                else {
                    port = 2014;
                    portfla = 2;
                }
                IPEndPoint ipe = new IPEndPoint(ip, port);
                //创建Socket并开始监听

                Socket s = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); //创建一个Socket对象，如果用UDP协议，则要用SocketTyype.Dgram类型的套接字
                s.Bind(ipe);    //绑定EndPoint对象(2000端口和ip地址)
                s.Listen(0);    //开始监听
                while (runOrstop)
                {
                    try
                    {
                        Console.WriteLine("等待客户端连接");
                        //接受到Client连接，为此连接建立新的Socket，并接受消息
                        Socket temp = s.Accept();   //为新建立的连接创建新的Socket
                        Console.WriteLine("建立连接");
                        string recvStr = "";
                        byte[] recvBytes = new byte[1024];
                        int bytes;
                        bytes = temp.Receive(recvBytes, recvBytes.Length, 0); //从客户端接受消息
                        recvStr += Encoding.ASCII.GetString(recvBytes, 0, bytes);
                        //给Client端返回信息
                        Console.WriteLine("server get message:{0}", recvStr);    //把客户端传来的信息显示出来
                        string sendStr = "ok";
                        byte[] bs = Encoding.ASCII.GetBytes(sendStr);
                        temp.Send(bs, bs.Length, 0);  //返回信息给客户端
                        temp.Close();
                        //消息指令判断
                        //定义消息格式
                        //-01-内容-
                        if (recvStr.StartsWith("-01"))
                        {
                            //开始考试，指定窗体最小化
                            Console.WriteLine("开始考试。。窗体最小化");
                            minWinForm();
                        }
                        else if (recvStr.StartsWith("-02"))
                        {
                            //结束考试，弹出警告窗体，禁用外接设备，禁用 任务管理器
                            Console.WriteLine("考试结束，禁用设备。。");
                            stopDevices();
                        }
                        else if (recvStr.StartsWith("-03"))
                        {
                            //教师发布命令，解除禁用，关闭警告窗体
                            Console.WriteLine("教师命令，解除禁用。。");
                            startDevices();
                            Console.WriteLine("程序退出。");
                            exitWinForm();
                        }
                        else if (recvStr.StartsWith("-04"))
                        {
                            //命令退出客户端
                            Console.WriteLine("教师命令退出客户端");
                            exitWinForm();
                        }
                    }
                    catch (Exception e) {
                        Console.WriteLine("错误："+e);
                    }
                }
                s.Close();
                  }

        private void notifyIcon1_MouseDoubleClick(object sender, MouseEventArgs e)
        {
            this.Show();
            this.WindowState = FormWindowState.Normal;
            notifyIcon1.Visible = false;
            this.ShowInTaskbar = true;
        }
        //最小化窗体到系统托盘
        private void minWinForm() {
            if (InvokeRequired)
            {
                GoDelegate godelegate = new GoDelegate(minWinForm);
                this.Invoke(godelegate);
            }
            else {
                notifyIcon1.Visible = true;
                Hide();
            }
        }
        //禁用设备，弹出警告
        private void stopDevices()
        {
            if (InvokeRequired)
            {
                GoDelegate godelegate = new GoDelegate(stopDevices);
                this.Invoke(godelegate);
            }
            else
            {
                BlockInput(true);//锁定鼠标及键盘
                this.Visible = false;
                warring wa = new warring();
                wa.Visible = true;
                wa.Show();
            }
        }
        //解除禁用，撤销警告
        private void startDevices()
        {
            if (InvokeRequired)
            {
                GoDelegate godelegate = new GoDelegate(startDevices);
                this.Invoke(godelegate);
            }
            else
            {
                BlockInput(false);//解除鼠标及键盘锁定
                this.Visible = true;
                if(ks!=null)
                ks.Dispose();
            }
        }
        //退出客户端
        private void exitWinForm()
        {
            if (InvokeRequired)
            {
                GoDelegate godelegate = new GoDelegate(exitWinForm);
                this.Invoke(godelegate);
            }
            else
            {
                cadstop.UnregisterHotKey(Handle, 100);   //注销Id号为101的热键设定  
                cadstop.UnregisterHotKey(Handle, 101);   //注销Id号为102的热键设定   
                cadstop.UnregisterHotKey(Handle, 102);   //注销Id号为103的热键设定   
                cadstop.UnregisterHotKey(Handle, 103);
                cadstop.Hook_Clear();
                cadstop.TaskMgrLocking(false);
                Environment.Exit(0);
            }
        }

        private void main_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (canclose)
            { 
                exitWinForm();
            }
            else {
                e.Cancel = true;
            }
        }
      }
    }
